Page({
    data: {
        bgImgs: ['card-bg2.jpg', 'card-bg1.jpg', 'card-bg3.jpg'],
        activeBg: 0,
        qrCodeConfig: [{
            color: '#fff',
            bottom: '180rpx',
            buttonBg: '#CC0507',
        }, {
            color: '#333',
            bottom: '105rpx',
            buttonBg: '#CC0507',
        }, {
            color: '#fff',
            bottom: '200rpx',
            buttonBg: '#CC0507',
        }],
        canvasWidth: '', //canvas宽
        canvasHeight: '', //canvas高
        scale: 1, //缩放比例
        posterLogo: "", //分享海报小程序码的本地路径
        sharePosterPath: "", //生成的海报本地图片路径
    },
    onLoad() {
        /**
         * 图片宽高比例 1/2.13
         * 固定canvas高度416px
         * 计算canvas宽度 426/2.13 = 200px
         * canvas增加上下左右10px边框
         * 416 + 20
         * 200 + 20
         */
        let bgwidth = 828
        let bgHeight = 1762
        let canvasWidth = 400
        let canvasHeight = Number((bgHeight * canvasWidth / bgwidth).toFixed(2))
        let scale = Number((bgwidth / canvasWidth).toFixed(2))
        this.setData({
            canvasWidth: canvasWidth + 20,
            canvasHeight: canvasHeight + 20,
            scale,
        })
    },
    priview() {
        wx.previewImage({
            urls: [this.data.imgHost + this.data.userInfo.invite_qrcode]
        })
    },
    onSwiperChange(e) {
        this.setData({
            activeBg: e.detail.index,
            sharePosterPath: '',
        })

        wx.pageScrollTo({
            scrollTop: 0,
            duration: 0
        })
    },
    /**点击切换背景图 */
    previous() {
        let { activeBg } = this.data
        activeBg--
        if (activeBg === -1) activeBg = this.data.bgImgs.length - 1
        this.setData({ activeBg })
    },
    next() {
        let { activeBg } = this.data
        activeBg++
        if (activeBg > this.data.bgImgs.length - 1) activeBg = 0
        this.setData({ activeBg })
    },
    generatePoster: function(e) {
        if (this.data.sharePosterPath) {
            return this.preservationPostImage()
        }
        wx.showLoading({
            title: '海报生成中...',
            icon: 'loading'
        })
        let that = this
        wx.getImageInfo({
            src: that.data.imgHost + that.data.userInfo.invite_qrcode,
            success(result) {
                that.setData({
                    posterLogo: result.path
                })
                that.createNewImg()
            }
        })
    },
    //将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
    createNewImg: function() {
        let that = this;
        let { canvasWidth, canvasHeight, bgImgs, activeBg, scale } = that.data
        var context = wx.createCanvasContext('canvas_poster');
        context.draw() //清空
        context.clearRect(0, 0, canvasWidth, canvasHeight);
        context.setFillStyle("#fff")
        context.fillRect(0, 0, canvasWidth, canvasHeight)
        context.save(); //保存之前的画布设置

        //绘制背景图片
        var posterBg = '/assets/img/' + bgImgs[activeBg];
        // 图片的x坐标
        let bg_x = 10
        // 图片的y坐标
        let bg_y = 10
        // 图片宽度
        let bg_w = canvasWidth - 20
        // 图片高度
        let bg_h = canvasHeight - 20
        // 图片圆角
        let bg_r = 10

        context.beginPath()
        context.arc(bg_x + bg_r, bg_y + bg_r, bg_r, Math.PI, Math.PI * 1.5)
        context.arc(bg_x + bg_w - bg_r, bg_y + bg_r, bg_r, Math.PI * 1.5, Math.PI * 2)
        context.arc(bg_x + bg_w - bg_r, bg_y + bg_h - bg_r, bg_r, 0, Math.PI * 0.5)
        context.arc(bg_x + bg_r, bg_y + bg_h - bg_r, bg_r, Math.PI * 0.5, Math.PI)
        context.clip() //裁剪
        context.drawImage(posterBg, 10, 10, bg_w, bg_h);
        context.restore() //因为clip是剪切了画布  则后面所有的操作都会限制在被裁减的区域内可见  用restore可以恢复之前的设置

        //文字
        context.setFillStyle(activeBg === 1 ? '#333' : '#fff');
        that.dealWords({
            ctx: context, //画布上下文 canvasID
            fontWeight: 'bold',
            fontSize: 18, //字体大小
            word: '蚂蚁花团', //需要处理的文字
            maxWidth: 180, //一行文字最大宽度
            x: canvasWidth / 2 - 32, //文字在x轴要显示的位置
            y: canvasHeight - (activeBg === 1 ? 150 : 200), //文字在y轴要显示的位置
            maxLine: 1 //文字最多显示的行数
        });

        that.dealWords({
            ctx: context, //画布上下文 canvasID
            fontWeight: 400,
            fontSize: 14, //字体大小
            word: '领先的花农鲜花直卖平台', //需要处理的文字
            maxWidth: 180, //一行文字最大宽度
            x: canvasWidth / 2 - 75, //文字在x轴要显示的位置
            y: canvasHeight - (activeBg === 1 ? 125 : 175), //文字在y轴要显示的位置
            maxLine: 1 //文字最多显示的行数
        });


        //绘制分享二维码
        var posterLogo = that.data.posterLogo;
        //添加圆角
        // 图片宽度
        let qr_code_w = 240 / scale
        // 图片高度
        let qr_code_h = 240 / scale
        // 图片圆角
        let qr_code_r = 5
        // 图片的x坐标
        let qr_code_x = canvasWidth / 2 - (qr_code_w / 2)
        // 图片的y坐标
        let qr_code_y = canvasHeight - (activeBg === 1 ? 270 : 320)

        context.beginPath()
        context.arc(qr_code_x + qr_code_r, qr_code_y + qr_code_r, qr_code_r, Math.PI, Math.PI * 1.5)
        context.arc(qr_code_x + qr_code_w - qr_code_r, qr_code_y + qr_code_r, qr_code_r, Math.PI * 1.5, Math.PI * 2)
        context.arc(qr_code_x + qr_code_w - qr_code_r, qr_code_y + qr_code_h - qr_code_r, qr_code_r, 0, Math.PI * 0.5)
        context.arc(qr_code_x + qr_code_r, qr_code_y + qr_code_h - qr_code_r, qr_code_r, Math.PI * 0.5, Math.PI)
        context.clip() //裁剪
        context.drawImage(posterLogo, qr_code_x, qr_code_y, qr_code_w, qr_code_h);
        context.restore() //因为clip是剪切了画布  则后面所有的操作都会限制在被裁减的区域内可见  用restore可以恢复之前的设置

        context.draw(true, () => {
            wx.canvasToTempFilePath({
                canvasId: 'canvas_poster',
                success: function(res) {
                    let tempFilePath = res.tempFilePath;
                    that.setData({
                        sharePosterPath: tempFilePath,
                        // maskHidden: true
                    })
                    that.preservationPostImage()
                },
                complete() {
                    wx.hideLoading()
                }
            })
        }); //true表示保留之前绘制内容
    },
    //canvas文本换行
    dealWords(options) {
        // options.ctx.setFontSize(options.fontSize); //设置字体大小
        options.ctx.font = options.fontWeight + ' ' + options.fontSize + 'px normal';
        var allRow = Math.ceil(options.ctx.measureText(options.word).width / options.maxWidth); //实际总共能分多少行
        var count = allRow >= options.maxLine ? options.maxLine : allRow; //实际能分多少行与设置的最大显示行数比，谁小就用谁做循环次数

        var endPos = 0; //当前字符串的截断点
        for (var j = 0; j < count; j++) {
            var nowStr = options.word.slice(endPos); //当前剩余的字符串
            var rowWid = 0; //每一行当前宽度    
            if (options.ctx.measureText(nowStr).width > options.maxWidth) { //如果当前的字符串宽度大于最大宽度，然后开始截取
                for (var m = 0; m < nowStr.length; m++) {
                    rowWid += options.ctx.measureText(nowStr[m]).width; //当前字符串总宽度
                    if (rowWid > options.maxWidth) {
                        if (j === options.maxLine - 1) { //如果是最后一行
                            options.ctx.fillText(nowStr.slice(0, m - 1) + '...', options.x, options.y + (j + 1) * 25); //(j+1)*20这是每一行的高度        
                        } else {
                            options.ctx.fillText(nowStr.slice(0, m), options.x, options.y + (j + 1) * 25);
                        }
                        endPos += m; //下次截断点
                        break;
                    }
                }
            } else { //如果当前的字符串宽度小于最大宽度就直接输出
                options.ctx.fillText(nowStr.slice(0), options.x, options.y + (j + 1) * 25);
            }
        }
    },
    //点击保存到相册
    preservationPostImage: function() {
        var that = this
        wx.saveImageToPhotosAlbum({
            filePath: that.data.sharePosterPath,
            success(res) {
                wx.showModal({
                    content: '图片已保存至相册',
                    showCancel: false,
                    confirmText: '我知道了',
                    confirmColor: '#188075',
                })
            },
            fail() {
                that.openSetting()
            }
        })
    },
    //打开授权设置
    openSetting() {
        wx.getSetting({
            success(res) {
                if (res.authSetting["scope.writePhotosAlbum"] === false) { //用户拒绝授权保存图片至相册
                    wx.showModal({
                        title: '提示',
                        content: '请允许保存至相册权限',
                        showCancel: false,
                        confirmColor: '#188075',
                        success() {
                            wx.openSetting()
                        }
                    })
                }
            }
        })
    }
})